package com.studentmanagement.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.studentmanagement.model.Course;
import com.studentmanagement.model.Enrollment;
import com.studentmanagement.model.PageBean;
import com.studentmanagement.model.Student;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.service.EnrollmentService;
import com.studentmanagement.service.StudentService;

@Controller
@RequestMapping("/enrollment")
public class EnrollmentController {

    @Autowired
    private EnrollmentService enrollmentService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 显示选课记录列表
     */
    @GetMapping("")
    public String list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                       @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                       @RequestParam(value = "sortField", defaultValue = "enrollmentId") String sortField,
                       @RequestParam(value = "sortOrder", defaultValue = "ASC") String sortOrder,
                       Model model) {
        // 获取分页数据
        PageBean<Enrollment> pageBean = enrollmentService.getEnrollmentsByPage(pageNum, pageSize, sortField, sortOrder);

        // 将数据存入  pageSize, sortField, sortOrder);

        // 将数据存入模型
        model.addAttribute("pageBean", pageBean);

        return "enrollment/list";
    }

    /**
     * 显示添加选课记录表单
     */
    @GetMapping("/add")
    public String showAddForm(Model model) {
        // 获取所有学生和课程，用于下拉选择
        List<Student> students = studentService.getAllStudents();
        List<Course> courses = courseService.getAllCourses();

        model.addAttribute("students", students);
        model.addAttribute("courses", courses);

        return "enrollment/add";
    }

    /**
     * 处理添加选课记录请求
     */
    @PostMapping("/add")
    public String add(@RequestParam("studentId") Integer studentId,
                      @RequestParam("courseId") Integer courseId,
                      @RequestParam("enrollmentDate") String enrollmentDateStr,
                      @RequestParam(value = "grade", required = false) String grade,
                      Model model) {
        try {
            // 解析日期
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);

            // 创建选课记录对象
            Enrollment enrollment = new Enrollment();
            enrollment.setStudentId(studentId);
            enrollment.setCourseId(courseId);
            enrollment.setEnrollmentDate(enrollmentDate);
            enrollment.setGrade(grade);

            // 添加选课记录
            boolean success = enrollmentService.addEnrollment(enrollment);

            if (success) {
                // 添加成功，重定向到列表页面
                return "redirect:/enrollment";
            } else {
                // 添加失败，设置错误消息
                model.addAttribute("error", "添加选课记录失败");

                // 重新获取学生和课程列表
                List<Student> students = studentService.getAllStudents();
                List<Course> courses = courseService.getAllCourses();

                model.addAttribute("students", students);
                model.addAttribute("courses", courses);

                return "enrollment/add";
            }
        } catch (ParseException e) {
            e.printStackTrace();
            model.addAttribute("error", "日期格式错误");

            // 重新获取学生和课程列表
            List<Student> students = studentService.getAllStudents();
            List<Course> courses = courseService.getAllCourses();

            model.addAttribute("students", students);
            model.addAttribute("courses", courses);

            return "enrollment/add";
        }
    }

    /**
     * 显示编辑选课记录表单
     */
    @GetMapping("/edit")
    public String showEditForm(@RequestParam("id") Integer enrollmentId, Model model) {
        // 获取选课记录信息
        Enrollment enrollment = enrollmentService.getEnrollmentById(enrollmentId);

        if (enrollment != null) {
            // 获取所有学生和课程，用于下拉选择
            List<Student> students = studentService.getAllStudents();
            List<Course> courses = courseService.getAllCourses();

            model.addAttribute("students", students);
            model.addAttribute("courses", courses);

            // 将选课记录信息存入模型
            model.addAttribute("enrollment", enrollment);

            return "enrollment/edit";
        } else {
            // 选课记录不存在，重定向到列表页面
            return "redirect:/enrollment";
        }
    }

    /**
     * 处理编辑选课记录请求
     */
    @PostMapping("/edit")
    public String edit(@RequestParam("enrollmentId") Integer enrollmentId,
                       @RequestParam("studentId") Integer studentId,
                       @RequestParam("courseId") Integer courseId,
                       @RequestParam("enrollmentDate") String enrollmentDateStr,
                       @RequestParam(value = "grade", required = false) String grade,
                       Model model) {
        try {
            // 解析日期
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);

            // 创建选课记录对象
            Enrollment enrollment = new Enrollment();
            enrollment.setEnrollmentId(enrollmentId);
            enrollment.setStudentId(studentId);
            enrollment.setCourseId(courseId);
            enrollment.setEnrollmentDate(enrollmentDate);
            enrollment.setGrade(grade);

            // 更新选课记录
            boolean success = enrollmentService.updateEnrollment(enrollment);

            if (success) {
                // 更新成功，重定向到列表页面
                return "redirect:/enrollment";
            } else {
                // 更新失败，设置错误消息
                model.addAttribute("error", "更新选课记录失败");
                model.addAttribute("enrollment", enrollment);

                // 重新获取学生和课程列表
                List<Student> students = studentService.getAllStudents();
                List<Course> courses = courseService.getAllCourses();

                model.addAttribute("students", students);
                model.addAttribute("courses", courses);

                return "enrollment/edit";
            }
        } catch (ParseException e) {
            e.printStackTrace();
            model.addAttribute("error", "日期格式错误");

            // 获取原选课记录信息
            Enrollment enrollment = enrollmentService.getEnrollmentById(enrollmentId);
            model.addAttribute("enrollment", enrollment);

            // 重新获取学生和课程列表
            List<Student> students = studentService.getAllStudents();
            List<Course> courses = courseService.getAllCourses();

            model.addAttribute("students", students);
            model.addAttribute("courses", courses);

            return "enrollment/edit";
        }
    }

    /**
     * 处理删除选课记录请求
     */
    @GetMapping("/delete")
    public String delete(@RequestParam("id") Integer enrollmentId) {
        // 删除选课记录
        enrollmentService.deleteEnrollment(enrollmentId);

        // 重定向到列表页面
        return "redirect:/enrollment";
    }
}